//引入核心类
import QQMapWX from "../../../../../libs/qqmap-wx-jssdk";
// import Schema from 'async-validator'
import Schema from "async-validator";
import {
  reqAddAddress,
  reqAddressInfo,
  reqUpdateAddress,
} from "../../../../../api/address";
Page({
  // 页面的初始数据
  data: {
    name: "", // 收货人
    phone: "", // 手机号
    provinceName: "", // 省
    provinceCode: "", // 省 编码
    cityName: "", // 市
    cityCode: "", // 市 编码
    districtName: "", // 区
    districtCode: "", // 区 编码
    address: "", // 详细地址
    fullAddress: "", // 完整地址 (省 + 市 + 区 + 详细地址)
    isDefault: false, // 设置默认地址，是否默认地址 → 0：否  1：是
  },

  // 保存收货地址
  async saveAddrssForm(event) {
    const {
      provinceName,
      cityName,
      districtName,
      address,
      isDefault,
    } = this.data;

    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0,
    };

    const { valid } = await this.validatorAddress(params);

    if (!valid) return;

    const res = this.addressId
      ? await reqUpdateAddress(params)
      : await reqAddAddress(params);
    // console.log(res);
    if (res.code === 200) {
      wx.navigateBack();

      wx.toast({  title: this.addressId ? "更新收货地址成功" : "新增收货地址成功" });
    }
  },

  validatorAddress(params) {
    // 验证收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = "^[a-zA-Z\\d\\u4e00-\\u9fa5]+$";

    // 验证手机号，是否符合中国大陆手机号码的格式
    const phoneReg =
      "^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$";

    const rules = {
      name: [
        { required: true, message: "请输入收货人姓名" },
        { pattern: nameRegExp, message: "收货人姓名不合法" },
      ],
      phone: [
        { required: true, message: "请输入收货人手机号" },
        { pattern: phoneReg, message: "收货人手机号不合法" },
      ],
      provinceName: { required: true, message: "请选择收货人所在地区" },
      address: { required: true, message: "请输入详细地址" },
    };

    const validator = new Schema(rules);

    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          wx.toast({ title: errors[0].message });
          resolve({ valid: false });
        } else {
          resolve({ valid: true });
        }
      });
    });
  },

  // 省市区选择
  onAddressChange(event) {
    const [provinceName, cityName, districtName] = event.detail.value;
    const [provinceCode, cityCode, districtCode] = event.detail.code;

    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode,
    });
  },

  async onLocation() {
    // try {
    //   const res = await wx.getLocation();
    //   console.log(res);
    // } catch (error) {
    //   wx.toast({title:'你拒绝获取地理位置'})
    // }
    // const res = await wx.chooseLocation()
    const { latitude, longitude, name } = await wx.chooseLocation();
    // console.log(latitude, longitude, name);
    this.qqmapwx.reverseGeocoder({
      location: {
        longitude,
        latitude,
      },
      success: (res) => {
        // console.log(res);
        const { adcode, province, city, district } = res.result.ad_info;

        const { street, street_number } = res.result.address_component;

        const { standard_address } = res.result.formatted_addresses;
        console.log(standard_address);

        this.setData({
          provinceName: province,
          provinceCode: adcode.replace(adcode.substring(2, 6), "00"),

          cityName: city,
          cityCode: adcode.replace(adcode.substring(4, 6), "0000"),

          districtName: district,
          districtCode: district && adcode,

          address: street + street_number + name,
          fullAddress: standard_address + name,
        });
      },
    });
  },

  async showAddressInfo(id) {
    if (!id) return;

    this.addressId = id;

    wx.setNavigationBarTitle({
      title: "更新收货地址",
    });

    const { data } = await reqAddressInfo(id);

    this.setData(data);
  },

  onLoad(options) {
    this.qqmapwx = new QQMapWX({
      key: "TBWBZ-OHJKC-VCM27-ADNDO-RTIVJ-RAFGJ",
    });

    this.showAddressInfo(options.id);
  },
});
